<?php
/**
 * Created by PhpStorm.
 * User: chenxiaogang
 * Date: 2017/12/27
 * Time: 11:51
 */

namespace User\Controller;


use Common\Controller\AdminbaseController;
use User\Model\LoanOperationLogModel;
use User\Model\LoanReceivedLogModel;
use User\Model\Orders;
use User\Model\User;

/**
 * Class AfterloanController
 * @package     User\Controller
 * @description 贷后订单操作
 * @end
 */
class AfterloanController extends AdminbaseController
{
    /**
     * @var [订单模型]
     */
    private $orderModel;
    /**
     * @var [用户模型]
     */
    private $userModel;

    public function _initialize()
    {
        $this->orderModel = M( 'ders', 'or', C( 'DB_CONFIG2' ) );
        $this->userModel = M( 'user', 'system_', C( 'DB_CONFIG2' ) );
        parent::_initialize();
    }

    /**
     * @use          [贷后操作列表]
     */
    public function index()
    {
        $page = I( 'p', 1 );
        $where = $this->get_after_order_condition();
        $fields_str = 'o.id,o.order_id,u.mobile,u.name,u.identity,o.amount,o.loan_day,o.stages,o.endtime,u.account_status,o.status,
                u.byusers,u.byusers_loan,u.code,o.loan_user';
        $this->list = $this->orderModel->alias( 'o' )
            ->field( $fields_str )
            ->join( 'system_user u ON u.id = o.user_id', 'LEFT' )
            ->where( $where )->page( $page, 20 )->select();

        //获取分页数据
        $count = $this->orderModel->alias( 'o' )
            ->join( 'system_user u ON u.id = o.user_id', 'LEFT' )
            ->where( $where )->count();
        $p_obj = $this->page( $count, 20 );
        $this->assign( "page", $p_obj->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到【贷后操作列表】查询条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_after_order_condition()
    {
        $where = [];
        //只能看到自己认领的订单
        //$where['_complex'] = [
        //    '_logic'=>'or',
        //    'u.byusers_loan_m1' => get_current_admin_id(),
        //    'u.byusers_loan_m2' => get_current_admin_id(),
        //];
        $where[] = '(u.byusers='.get_current_admin_id().' OR u.byusers_loan='.get_current_admin_id().' OR u.byusers_loan_m1='.get_current_admin_id().' OR u.byusers_loan_m2='.get_current_admin_id().')';
        //用户手机号
        $mobile = I( 'mobile' );
        if(!empty( $mobile )) {
            $where[] = 'u.mobile LIKE "%'.$mobile.'%"';
        }
        //用户昵称
        $name = I( 'name' );
        if(!empty( $name )) {
            $where[] = 'u.name LIKE "%'.$name.'%"';
        }
        $where = implode(' AND ',$where);
        return $where;
    }

    /**
     * @use          [贷后【收款登记】操作]
     * @author       chenxiaogang
     */
    public function after_loan_rev()
    {
        $oid = I( 'get.id', 0, 'int' );
        if(empty( $oid )) {
            $this->error( "传输错误！" );
        }
        $this->order = $order = $this->orderModel->find( $oid );//订单
        $model = new LoanOperationLogModel();
        if(IS_GET) {
            $this->user = $this->userModel->find( $order['user_id'] );//订单对应用户
            $where = [ 'ol.oid' => $oid ];
            $this->list = $model->get_list( $where );//历史操作记录
            $this->admins = (new User())->where( [ 'user_status' => 1 ] )->getField( 'id,user_login' );//管理员
            $this->display();
        } else {
            $options = I( 'post.options' );
            if(empty( $options['pay_way'] )) {
                $this->error( "至少选择一种收款方式" );
            }
            $datetime = date( 'Y-m-d H:i:s' );
            //先插入操作记录
            $opData = [
                'oid' => $oid,
                'user_id' => $order['user_id'],
                'platform' => $model::CURRENT_PLATFORM,
                'operation_date' => $options['operation_date'],
                'is_relief' => $options['is_relief'],
                'is_renewal' => $options['is_renewal'],
                'user_status' => $options['user_status'],
                'principal' => get_current_admin_id(),
                'create_time' => $datetime,
            ];
            //如果解套，则要记录解套平台和解套金额
            if(intval( $options['is_relief'] ) === 1) {
                $opData['relief_platform_txt'] = $options['relief_platform_txt'];
                $opData['relief_amount'] = $options['relief_amount'];
            }
            //如果有续期费，则记录续期金额
            if(intval( $options['is_renewal'] ) === 1) {
                $opData['renewal_amount'] = $options['renewal_amount'];
            }
            $model->startTrans();
            $opid = $model->add( $opData );

            $revData = [];//装收款记录
            foreach($options['pay_way'] as $v) {
                $v = intval( $v );
                $revData[] = [
                    'opid' => $opid,
                    'pay_way' => $v,//收款方式
                    'rev_amount' => $options['rev_amount_' . $v],
                    'rev_admin_id' => $v == 0 ? 0 : $options['rev_admin_id_' . $v],
                    'rev_time' => $datetime,
                ];
            }
            $loanReceivedLogModel = new LoanReceivedLogModel();
            $r = $loanReceivedLogModel->addAll( $revData );
            if($opid > 0 && $r > 0) {
                $model->commit();
                $this->success( '登记成功', U( 'afterloan/index' ) );
            } else {
                $model->rollback();
                $this->error( '登记失败'.' '.$opid.' '.$r.' '.json_encode($model->getDbError()) );
            }
        }
    }

    /**
     * @use          [核准列表]
     * @author       chenxiaogang
     */
    public function audit_list()
    {
        $model = new LoanOperationLogModel();
        $where = $this->get_audit_list_condition();
        $count = $model->get_audit_list_count( $where );
        $page = $this->page( $count, 20 );
        $limit = $page->firstRow . ',' . $page->listRows;
        $this->list = $model->get_audit_list( $where, $limit );
        //组装订单号、用户、手机、操作人、各种收款方式的收款人、核对人
        if(!empty( $this->list )) {
            $oids = $userIds = $adminIds = [];
            foreach($this->list as $v) {
                $oids[] = $v['oid'];
                $userIds[] = $v['user_id'];
                $adminIds[] = $v['check_admin_id'];
                $adminIds[] = $v['principal'];
                $adminIds[] = $v['wechat_rev_admin_id'];
                $adminIds[] = $v['alipay_rev_admin_id'];
                $adminIds[] = $v['bank_rev_admin_id'];
            }
            $adminIds = array_values( array_unique( array_filter( $adminIds ) ) );
            if(!empty( $oids )) {
                $this->orders = (new Orders())->where( [ 'id' => [ 'in', $oids ] ] )->getField( 'id,order_id' );
            }
            if(!empty( $userIds )) {
                $this->users = $this->userModel->where( [ 'id' => [ 'in', $userIds ] ] )->getField( 'id,name,mobile', true );
            }
            if(!empty( $adminIds )) {
                $this->admins = (new User())->getbyIn( $adminIds );
            }
        }
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到【核准列表】查询条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_audit_list_condition()
    {
        $where = $userWhere = [];
        if($mobile = I( 'request.mobile' )) {
            $userWhere['mobile'] = [ 'like', $mobile . '%' ];
        }
        if($name = I( 'request.name' )) {
            $userWhere['name'] = [ 'like', '%' . $name . '%' ];
        }
        //如果接受到电话或者姓名的条件，则查询出用户ID列表，作为新条件
        if($mobile || $name) {
            $userIds = $this->userModel->where( $userWhere )->getField( 'id', true );
            $where['user_id'] = [ 'in', $userIds ];
        }
        //查询登记人（管理员）ID列表，作为新条件
        if($principal = I( 'request.principal' )) {
            $adminIds = (new User())->where( [ 'user_login' => [ 'like', '%' . $principal . '%' ], 'user_status' => 1 ] )->getField( 'id', true );
            if(!empty( $adminIds )) {
                $where['principal'] = [ 'in', $adminIds ];
            }
        }
        if($operation_date = I( 'request.operation_date' )) {
            $where['operation_date'] = $operation_date;
        }
        //是否核准
        if('' !== I('request.is_check')){
            $where['is_check'] = I('request.is_check');
        }
        return $where;
    }

    /**
     * @use          [核对 - 批量操作]
     * @author       chenxiaogang
     */
    public function audit()
    {
        $model = new LoanOperationLogModel();
        $ids = I( 'post.id' );
        //将未核对的记录，改成已核对
        $r = $model->where( [
            'id' => [ 'in', $ids ],//前台传过来的需要核对的记录
            'is_check' => 0,
        ] )->save( [
            'is_check' => 1,
            'check_admin_id' => get_current_admin_id(),
            'check_time' => date( 'Y-m-d H:i:s' ),
        ] );
        if($r > 0) {
            $this->success( '核对成功', U( 'afterloan/audit_list' ) );
        } elseif($r == 0) {
            $this->success( '已核准，无需核准', U( 'afterloan/audit_list' ) );
        } else {
            $this->error( '核对失败' );
        }
    }

    /**
     * @use          [批量强制删除贷后操作记录]
     * @author       chenxiaogang
     */
        public function force_del()
    {
        $model = new LoanOperationLogModel();
        $loanReceivedLogModel = new LoanReceivedLogModel();
        $ids = trim(I( 'post.id' ),',');//操作记录主键
        $model->startTrans();
        //删除贷后操作收款记录
        $r1 = $loanReceivedLogModel->where(['opid'=>$ids])->delete();
        $r2 = $model->where(['id' => [ 'in', $ids ]])->delete();
        if($r1 > 0 && $r2 >0) {
            $model->commit();
            $this->success( '删除成功', U( 'afterloan/audit_list' ) );
        } else {
            $model->rollback();
            $this->error( '删除失败' );
        }
    }

    /**
     * @use          [普通批量删除 - 不能删除已核准的]
     * @author       chenxiaogang
     */
    public function del()
    {
        $model = new LoanOperationLogModel();
        $loanReceivedLogModel = new LoanReceivedLogModel();
        $ids = trim(I( 'post.id' ),',');//操作记录主键
        $model->startTrans();
        //删除贷后操作收款记录
        $r1 = $loanReceivedLogModel->where(['opid'=>$ids])->delete();
        $r2 = $model->where(['id' => [ 'in', $ids ],'is_check' => 0])->delete();
        if($r1 > 0 && $r2 > 0 ) {
            $model->commit();
            $this->success( '删除成功', U( 'afterloan/audit_list' ) );
        } else if($r1 > 0 && $r2 == 0){
            $model->rollback();
            $this->error( '只能删除待核准的记录' );
        } else {
            $model->rollback();
            $this->error( '删除失败' );
        }
    }

    /**
     * @use          [贷后操作统计]
     * @author       chenxiaogang
     */
    public function report()
    {
        $model = new LoanOperationLogModel();
        $where = $this->get_report_conditoin();
        $this->list = $model->get_report( $where );
        $this->count = $model->get_report_count( $where );
        //组装订单号、用户、手机、操作人、各种收款方式的收款人、核对人
        if(!empty( $this->list )) {
            $adminIds = array_values( array_unique( array_filter( array_column( $this->list, 'principal' ) ) ) );
            if(!empty( $adminIds )) {
                $this->admins = (new User())->getbyIn( $adminIds );
            }
        }
        $this->display();
    }

    /**
     * @use          [得到贷后操作统计的条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_report_conditoin()
    {
        $where = [];
        //查询登记人（管理员）ID列表，作为新条件
        if($principal = I( 'request.principal' )) {
            $adminIds = (new User())->where( [ 'user_login' => [ 'like', '%' . $principal . '%' ], 'user_status' => 1 ] )->getField( 'id', true );
            if(!empty( $adminIds )) {
                $where['principal'] = [ 'in', $adminIds ];
            }
        }
        //用时间过滤统计数据
        if($operation_date_start = I( 'request.operation_date_start' )) {
            $where['operation_date'] = [ 'EGT', $operation_date_start ];
        }
        if($operation_date_end = I( 'request.operation_date_end' )) {
            $where[' operation_date'] = [ 'ELT', $operation_date_end ];
        }

        //必须条件：
        $where['is_check'] = 1;//核准后才能纳入统计
        return $where;
    }

    /**
     * @use          [登记人操作详情列表]
     * @author       chenxiaogang
     */
    public function report_user_detail()
    {
        $this->principal = I( 'get.principal' );
        $model = new LoanOperationLogModel();
        $where['principal'] = $this->principal;
        $where = array_merge( $where, $this->get_report_user_detail_condition() );
        $count = $model->get_audit_list_count( $where );
        $page = $this->page( $count, 20 );
        $limit = $page->firstRow . ',' . $page->listRows;
        $this->list = $model->get_audit_list( $where, $limit );
        //组装订单号、用户、手机、操作人、各种收款方式的收款人、核对人
        if(!empty( $this->list )) {
            $oids = $userIds = $adminIds = [];
            foreach($this->list as $v) {
                $oids[] = $v['oid'];
                $userIds[] = $v['user_id'];
                $adminIds[] = $v['check_admin_id'];
                $adminIds[] = $v['principal'];
                $adminIds[] = $v['wechat_rev_admin_id'];
                $adminIds[] = $v['alipay_rev_admin_id'];
                $adminIds[] = $v['bank_rev_admin_id'];
            }
            $adminIds = array_values( array_unique( array_filter( $adminIds ) ) );
            if(!empty( $oids )) {
                $this->orders = (new Orders())->where( [ 'id' => [ 'in', $oids ] ] )->getField( 'id,order_id' );
            }
            if(!empty( $userIds )) {
                $this->users = $this->userModel->where( [ 'id' => [ 'in', $userIds ] ] )->getField( 'id,name,mobile', true );
            }
            if(!empty( $adminIds )) {
                $this->admins = (new User())->getbyIn( $adminIds );
            }
            //获取合计
            $this->total = $model->get_report_detail_total($where);
        }
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到登记人操作详情列表的条件]
     * @author       chenxiaogang
     * @return array
     */
    private function get_report_user_detail_condition()
    {
        $where = $userWhere = [];
        if($mobile = I( 'request.mobile' )) {
            $userWhere['mobile'] = [ 'like', $mobile . '%' ];
        }
        if($name = I( 'request.name' )) {
            $userWhere['name'] = [ 'like', '%' . $name . '%' ];
        }
        //如果接受到电话或者姓名的条件，则查询出用户ID列表，作为新条件
        if($mobile || $name) {
            $userIds = $this->userModel->where( $userWhere )->getField( 'id', true );
            $where['user_id'] = [ 'in', $userIds ];
        }
        //用时间过滤统计数据
        if($operation_date_start = I( 'request.operation_date_start' )) {
            $where['operation_date'] = [ 'EGT', $operation_date_start ];
        }
        if($operation_date_end = I( 'request.operation_date_end' )) {
            $where[' operation_date'] = [ 'ELT', $operation_date_end ];
        }
        //必须条件：
        $where['is_check'] = 1;//核准后才能纳入统计
        return $where;
    }


}